import React from "react";
import { Button, Form, Input, Space, Table, Modal, message } from "antd";
import { PlusOutlined, EditOutlined, DeleteOutlined } from "@ant-design/icons";
import { InspectionAreaItem, getInspectionAreaList, createInspectionArea, updateInspectionArea, deleteInspectionArea } from "../../api/gis";
import { useEffect, useState } from "react";
import { useRef } from "react";

interface Props {
  planetId: number;
  reloadFlag?: number;
  onChanged?: () => void;
}

const InspectionAreaPanel: React.FC<Props> = ({ planetId, reloadFlag = 0, onChanged }) => {
  const [data, setData] = useState<InspectionAreaItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [total, setTotal] = useState(0);
  const [modalOpen, setModalOpen] = useState(false);
  const [editing, setEditing] = useState<InspectionAreaItem | null>(null);
  const [form] = Form.useForm();

  // 表格容器与固定高度
  const tableContainerRef = useRef<HTMLDivElement | null>(null);
  const [tableScrollY, setTableScrollY] = useState<number>(0);

  const calculateTableScrollHeight = () => {
    if (tableContainerRef.current) {
      const pageHeight = window.innerHeight;
      const breadcrumbHeight = 48;
      const tabsHeaderHeight = 46;
      const filterFormHeight = 0;
      const actionButtonsHeight = 56;
      const padding = 242; // 与其他面板保持一致
      const availableHeight = pageHeight - breadcrumbHeight - tabsHeaderHeight - filterFormHeight - actionButtonsHeight - padding;
      const tableHeaderHeight = 39;
      const scrollHeight = Math.max(availableHeight - tableHeaderHeight, 100);
      setTableScrollY(scrollHeight);
      const tableBody = tableContainerRef.current.querySelector('.ant-table-body') as HTMLElement | null;
      if (tableBody) {
        tableBody.style.height = scrollHeight + 'px';
        tableBody.style.maxHeight = scrollHeight + 'px';
      }
    }
  };

  const fetchList = async () => {
    setLoading(true);
    try {
      const res = await getInspectionAreaList({ planet_id: planetId });
      if (res.code === 200) {
        setData(res.data.list);
        setTotal(res.data.count);
        setCurrent(res.data.page);
        setPageSize(res.data.page_size);
      }
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (planetId) fetchList();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [planetId, reloadFlag]);

  useEffect(() => {
    const timer = setTimeout(() => {
      calculateTableScrollHeight();
    }, 100);
    const onResize = () => calculateTableScrollHeight();
    window.addEventListener('resize', onResize);
    return () => {
      clearTimeout(timer);
      window.removeEventListener('resize', onResize);
    };
  }, []);
  const columns = [
    { title: "ID", dataIndex: "id", key: "id", width: 80, ellipsis: true },
    { title: "巡视区名称", dataIndex: "inspection_area_name", key: "inspection_area_name", width: 200, ellipsis: true },
    { title: "任务", dataIndex: "task", key: "task", width: 120, ellipsis: true },
    { title: "左纬度", dataIndex: "left_latitude", key: "left_latitude", width: 100, ellipsis: true },
    { title: "左经度", dataIndex: "left_longitude", key: "left_longitude", width: 100, ellipsis: true },
    { title: "右纬度", dataIndex: "right_latitude", key: "right_latitude", width: 100, ellipsis: true },
    { title: "右经度", dataIndex: "right_longitude", key: "right_longitude", width: 100, ellipsis: true },
    { title: "底图路径", dataIndex: "base_image_path", key: "base_image_path", width: 200, ellipsis: true },
    { title: "创建时间", dataIndex: "create_time", key: "create_time", width: 180, ellipsis: true },
    {
      title: "操作",
      key: "action",
      width: 200,
      fixed: "right" as const,
      align: "center" as const,
      render: (_: any, record: InspectionAreaItem) => (
        <Space size="small">
          <Button type="link" size="small" icon={<EditOutlined />} onClick={() => handleEdit(record)}>编辑</Button>
          <Button type="link" size="small" danger icon={<DeleteOutlined />} onClick={() => handleDelete(record)}>删除</Button>
        </Space>
      ),
    },
  ];

  const handleCreate = () => {
    setEditing(null);
    form.resetFields();
    setModalOpen(true);
  };

  const handleEdit = (record: InspectionAreaItem) => {
    setEditing(record);
    form.setFieldsValue({
      inspection_area_name: record.inspection_area_name,
      task: record.task,
      base_image_path: record.base_image_path,
    });
    setModalOpen(true);
  };

  const handleDelete = (record: InspectionAreaItem) => {
    Modal.confirm({
      title: "确认删除",
      content: `确定要删除巡视区 "${record.inspection_area_name}" 吗？`,
      okText: "确认",
      cancelText: "取消",
      onOk: async () => {
        const res = await deleteInspectionArea({ planet_id: planetId, inspection_area_ids: [record.id] });
        if (res.code === 200) {
          message.success("删除成功");
          fetchList();
          onChanged?.();
        } else {
          message.error(res.msg || "删除失败");
        }
      }
    });
  };

  const handleSave = async () => {
    const values = await form.validateFields();
    if (editing) {
      const res = await updateInspectionArea({ planet_id: planetId, id: editing.id, ...values });
      if (res.code === 200) {
        message.success("修改成功");
        setModalOpen(false);
        fetchList();
        onChanged?.();
      } else {
        message.error(res.msg || "修改失败");
      }
    } else {
      const res = await createInspectionArea({ planet_id: planetId, ...values });
      if (res.code === 200) {
        message.success("创建成功");
        setModalOpen(false);
        fetchList();
        onChanged?.();
      } else {
        message.error(res.msg || "创建失败");
      }
    }
  };

  return (
    <div style={{ height: "100%", display: "flex", flexDirection: "column" }}>
      {/* 筛选表单暂时隐藏 */}
      {/* <div style={{ flexShrink: 0 }}>
        <Form layout="inline" className="filter-form" labelCol={{ style: { width: 120 } }}>
          <Form.Item label="巡视区名称" style={{ width: 320 }}>
            <Input placeholder="请输入巡视区名称搜索" />
          </Form.Item>
          <Form.Item style={{ paddingLeft: 40 }}>
            <Space>
              <Button type="primary">筛选</Button>
              <Button>清除</Button>
            </Space>
          </Form.Item>
        </Form>
      </div> */}

      <div style={{ marginBottom: 16, marginTop: 16, display: "flex", justifyContent: "space-between", alignItems: "center", flexShrink: 0 }}>
        <div>
          <Button type="primary" danger disabled>
            批量删除
          </Button>
        </div>
        <Space>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
            新建巡视区
          </Button>
        </Space>
      </div>

      <div style={{ flex: 1, overflow: "hidden" }}>
        <div className="pds-table-container" style={{ height: "100%" }} ref={tableContainerRef}>
          <Table
            columns={columns}
            dataSource={data}
            rowKey="id"
            loading={loading}
            pagination={{
              current,
              pageSize,
              total,
              showSizeChanger: true,
              pageSizeOptions: ["10", "20", "50"],
              onChange: (p, s) => { setCurrent(p); setPageSize(s!); },
              showTotal: (t) => `共 ${t} 条`,
            }}
            scroll={{ y: tableScrollY, x: "max-content" }}
            bordered
            size="small"
          />
        </div>
      </div>

      <Modal title={editing ? "编辑巡视区" : "新建巡视区"} open={modalOpen} onOk={handleSave} onCancel={() => setModalOpen(false)} width={600} okText="保存" cancelText="取消">
        <Form form={form} layout="vertical" style={{ marginTop: 16 }}>
          <Form.Item name="inspection_area_name" label="巡视区名称" rules={[{ required: true, message: "请输入巡视区名称" }]}>
            <Input placeholder="请输入巡视区名称" />
          </Form.Item>
          <Form.Item name="task" label="任务" rules={[{ required: true, message: "请输入任务" }]}>
            <Input placeholder="请输入任务" />
          </Form.Item>
          <Form.Item name="base_image_path" label="底图路径" rules={[{ required: true, message: "请输入底图路径" }]}>
            <Input placeholder="请输入底图路径" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default InspectionAreaPanel;


